<script setup lang="ts">
import { submitUserFormAPI } from '@/apis/submitUserForm'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'

interface GetPriceCardProps {
  type: '1' | '2'
  isShowNameField?: boolean
}

const props = withDefaults(defineProps<GetPriceCardProps>(), {
  type: '1',
  isShowNameField: true,
})

const emit = defineEmits(['success'])

const projectConfigStore = useProjectConfigStore()
const userInfoStore = useUserInfoStore()

const formRef = ref<any>(null)

// 表单状态
const formData = ref({
  project_type: null as ProjectType | null,
  contact_name: props.isShowNameField ? '' : '无',
  contact_mobile: '',
  extent: null as Extent | null,
  province: '',
  city: '',
  district: '',
})

const rules = {
  project_type: { required: true, message: '装修类型不可为空' },
  contact_name: [
    { required: true, message: '您的称呼不可为空', trigger: ['blur', 'change'] },
    { pattern: /^[\u4E00-\u9FA5]+$/, message: '您的称呼只能包含中文', trigger: ['blur', 'change'] },
  ],
  contact_mobile: [
    { required: true, message: '您的手机号码不可为空', trigger: ['blur', 'change'] },
    {
      pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/,
      message: '请输入正确的手机号',
      trigger: ['blur'],
    },
  ],
  extent: { required: true, message: '面积不可为空' },
  province: { required: true, message: '省份不可为空' },
  city: { required: true, message: '城市不可为空' },
  district: { required: true, message: '区县不可为空' },
}

// 当 store 中的面积列表请求完成后，选中第一项
projectConfigStore.$subscribe((mutation, state) => {
  if (state.extentList.length > 0)
    formData.value.extent = state.extentList[0]
})

/* ------------------------------- 选择城市 START ------------------------------- */
const cityPickerPopupRef = ref<any>(null)
const selectedCityIndex = ref([0, 0, 0])

// 省市区字符串
const regionString = computed(() => {
  if (formData.value.province && formData.value.city && formData.value.district)
    return `${formData.value.province}${formData.value.city}${formData.value.district}`
})

function handleChangeCitySelection(newVal: any[]) {
  const indexes = newVal.map(item => item.index as number)
  selectedCityIndex.value = indexes
  const names = newVal.map(item => item.name as string)
  if (names.length > 2) {
    formData.value.province = names[0]
    formData.value.city = names[1]
    formData.value.district = names[2]
  }
}
/* -------------------------------- 选择城市 END -------------------------------- */

/* ------------------------------- 选择装修类型 START ------------------------------ */
function handleSelectProjectType() {
  uni.showActionSheet({
    itemList: projectConfigStore.projectTypeList.map(type => type.name),
    success: (result) => {
      formData.value.project_type = projectConfigStore.projectTypeList[result.tapIndex]
    },
  })
}
/* -------------------------------- 选择装修类型 END ------------------------------- */
function resetForm() {
  formData.value = {
    project_type: null,
    contact_name: props.isShowNameField ? '' : '无',
    contact_mobile: '',
    extent: projectConfigStore.extentList[0],
    province: '',
    city: '',
    district: '',
  }
}

const handleSubmit = useThrottleFn(() => {
  formRef.value.validate()
    .then(async () => {
      try {
        const res = await submitUserFormAPI({
          type: props.type,
          project_type_id: formData.value.project_type!.id!,
          contact_name: formData.value.contact_name,
          contact_mobile: formData.value.contact_mobile,
          extent_id: formData.value.extent!.id!,
          province: formData.value.province,
          city: formData.value.city,
          district: formData.value.district,
        }, userInfoStore.userInfo!.token!)
        if (res.data?.code === 1) {
          resetForm()
          emit('success')
        }
        else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
      }
      catch (error) {
        uni.showToast({ title: '提交失败，请稍后重试', icon: 'none' })
      }
    })
    .catch((errors: AnyObject[]) => {
      // 表单校验失败
      if (errors.length > 0)
        uni.showToast({ title: errors[0].message, icon: 'none' })
    })
}, 1000)
</script>

<template>
  <uv-form ref="formRef" :model="formData" :rules="rules">
    <!-- 选择城市 -->
    <uv-form-item prop="province" :custom-style="{ padding: 0 }">
      <view
        class="flex justify-between items-center px-30rpx w-full h-88rpx text-28rpx leading-28rpx bg-#F8F8F8 rounded-10rpx"
        :class="[regionString ? 'text-primary' : 'text-tertiary']"
        hover-class="bg-#F0F0F0"
        @tap.stop="cityPickerPopupRef.open()"
      >
        {{ regionString || '请选择城市' }}
        <image class="w-13rpx h-23rpx" src="@/static/images/cheveron-right.png" />
      </view>
    </uv-form-item>
    <Spacer height="24" />
    <!-- 选择装修类型 -->
    <uv-form-item prop="project_type" :custom-style="{ padding: 0 }">
      <view
        class="flex justify-between items-center px-30rpx w-full h-88rpx text-28rpx leading-28rpx bg-#F8F8F8 rounded-10rpx"
        :class="[formData.project_type?.name ? 'text-primary' : 'text-tertiary']"
        hover-class="bg-#F0F0F0"
        @tap.stop="handleSelectProjectType"
      >
        {{ formData.project_type?.name || '请选择装修类型' }}
        <image class="w-13rpx h-23rpx" src="@/static/images/cheveron-right.png" />
      </view>
    </uv-form-item>
    <Spacer height="24" />
    <!-- 填写姓名 -->
    <uv-form-item v-if="isShowNameField" prop="contact_name" :custom-style="{ padding: 0 }">
      <input
        v-model="formData.contact_name"
        placeholder="请输入您的称呼"
        class="px-30rpx w-full h-88rpx text-28rpx leading-28rpx text-primary bg-#F8F8F8 rounded-10rpx"
        placeholder-class="text-tertiary"
        :cursor-spacing="80"
      >
    </uv-form-item>
    <Spacer v-if="isShowNameField" height="24" />
    <!-- 填写手机号码 -->
    <uv-form-item prop="contact_mobile" :custom-style="{ padding: 0 }">
      <input
        v-model="formData.contact_mobile"
        placeholder="请输入您的手机号码"
        class="px-30rpx w-full h-88rpx text-28rpx leading-28rpx text-primary bg-#F8F8F8 rounded-10rpx"
        placeholder-class="text-tertiary"
        :cursor-spacing="80"
      >
    </uv-form-item>
    <Spacer height="24" />
    <!-- 选择面积大小 -->
    <uv-form-item :custom-style="{ padding: 0 }">
      <view v-if="projectConfigStore.extentList" class="flex justify-between items-center space-x-20rpx">
        <view
          v-for="item in projectConfigStore.extentList"
          :key="item.id"
          class="flex justify-center items-center w-full h-75rpx text-24rpx leading-24rpx rounded-10rpx"
          :class="[item.id === formData.extent?.id ? 'bg-brand text-white' : 'bg-#F8F8F8 text-primary']"
          @tap="formData.extent = item"
        >
          {{ item.name }}
        </view>
      </view>
      <!-- 占位 -->
      <view v-else class="flex justify-between items-center space-x-20rpx">
        <view
          v-for="i in 4"
          :key="i"
          class="flex justify-center items-center w-full h-75rpx text-24rpx leading-24rpx rounded-10rpx bg-#F8F8F8"
        />
      </view>
    </uv-form-item>
    <Spacer :height="type === '1' ? '50' : '80'" />
    <!-- 提交 -->
    <RGButton :width="type === '1' ? '630' : '422'" @tap="handleSubmit">
      免费获取{{ props.type === '1' ? '报价' : '户型规划' }}
    </RGButton>
  </uv-form>
  <uv-popup ref="cityPickerPopupRef" mode="bottom" round="10">
    <CityPicker
      :initial-value="selectedCityIndex"
      @change="handleChangeCitySelection"
      @close="cityPickerPopupRef.close()"
    />
  </uv-popup>
</template>
